#include "stdafx.h"
#include "SubscriptionsDlg.h"
#include "ListItemsDlg.h"
#include "ItemViewDlg.h"

#define MZ_IDC_LIST			101
#define MZ_IDC_TOOLBAR		102

CListItemsDlg g_ListItemsDlg;

CListItemsDlg::CListItemsDlg()
{
}

CListItemsDlg::~CListItemsDlg()
{
}

BOOL CListItemsDlg::OnInitDialog()
{
	if(!CMzWndEx::OnInitDialog()) return FALSE;

    mList.SetPos(0, 0, GetWidth(), GetHeight()-MZM_HEIGHT_TEXT_TOOLBAR);
    mList.SetID(MZ_IDC_LIST);
    mList.EnableScrollBarV(true);
    mList.EnableNotifyMessage(true);
    AddUiWin(&mList);

	mToolbar.SetPos(0, GetHeight()-MZM_HEIGHT_TEXT_TOOLBAR, GetWidth(), MZM_HEIGHT_TEXT_TOOLBAR);
    mToolbar.SetID(MZ_IDC_TOOLBAR);
    mToolbar.SetButton(0, true, true, L"Return");
    mToolbar.SetButton(1, false, true, L"Update");
    mToolbar.SetButton(2, false, true, L"Login");
    AddUiWin(&mToolbar);

	return TRUE;
}

LRESULT CListItemsDlg::MzDefWndProc(UINT message, WPARAM wParam, LPARAM lParam)
{
	if(message==MZ_WM_MOUSE_NOTIFY) {
		int nID = LOWORD(wParam);
		int nNotify = HIWORD(wParam);
		if(nID==MZ_IDC_LIST && nNotify==MZ_MN_LBUTTONDOWN) {
			int x = LOWORD(lParam);
			int y = HIWORD(lParam);
			if(!mList.IsMouseDownAtScrolling() && !mList.IsMouseMoved()) {
				int nIndex = mList.CalcIndexOfPos(x, y);
				mList.SetSelectedIndex(nIndex);
				mList.Invalidate();
				mList.Update();
			}
		}
		if(nID==MZ_IDC_LIST && nNotify==MZ_MN_MOUSEMOVE) {
			if(mList.GetSelectedIndex()!=-1) {
				mList.SetSelectedIndex(-1);
				mList.Invalidate();
				mList.Update();
			}
		}
		if(nID==MZ_IDC_LIST && nNotify==MZ_MN_LBUTTONUP) {
			if(mList.GetSelectedIndex()>=0) {
				int nCID = (int)(mList.GetItem(mList.GetSelectedIndex())->Data);
				g_ItemViewDlg.Active(MZ_ANIMTYPE_SCROLL_RIGHT_TO_LEFT_1, nCID);
			}
		}
	}

	return CMzWndEx::MzDefWndProc(message,wParam,lParam);
}

void CListItemsDlg::OnMzCommand(WPARAM wParam, LPARAM lParam)
{
	UINT_PTR id = LOWORD(wParam);

	if(id==MZ_IDC_TOOLBAR) {
		switch(lParam) {
		case 0:
			g_SubscriptionDlg.Active(MZ_ANIMTYPE_SCROLL_LEFT_TO_RIGHT_1);
			break;
		case 1:
			break;
		case 2:
			break;
		}
	}
}

void CListItemsDlg::Active(UINT nAnimType, int nSID)
{
	if(nSID!=-1) {
		mList.RemoveAll();
		mList.SetSelectedIndex(-1);

		std::vector<Item> List;
		if(!CReaderDatabase::GetSingleton().GetItems(nSID, List)) {
			MzMessageBoxEx(m_hWnd, L"ERROR GetItems", L"ERROR", MZ_OK);
			return;
		}

		ListItem li;
		TCHAR szTitle[300];
		for(size_t i=0; i<List.size(); i++) {
			if(!Utf8ToTCHAR(List[i].title.c_str(), szTitle, sizeof(szTitle))) {
				_tcscpy(szTitle, _T("Utf8ToTCHAR error"));
			}
			li.Data = (void*)List[i].cid;
			li.Text = szTitle;
			mList.AddItem(li);
		}
	}

    if(MzGetParam(MZGP_APP_START_ANIMATION)==TRUE) {
		AnimateWindow(nAnimType, true);
    }
	Show();
}
